<?php
/**
 * 消息模板
 * Created by PhpStorm.
 * User:
 * Date: 2017/4/26
 * Time: 15:07
 */

namespace App\Services;


use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;

use App\Services\AuthServices;

use App\Models\StaffOrder;
use App\Models\CarAuth;
use App\Models\CarAuthLog;
use App\Repositories\StaffOrderRepository;
use App\Repositories\CarAuthRepository;
use App\Repositories\CarAuthLogRepository;

use Monolog\Logger;
use Monolog\Handler\StreamHandler;



class CarAuthServices
{

    use AuthServices;

    public function __construct() {}


    // 下发授权
    public function issueAuth($staffOrder)
    {
        // staff authed parks
        $parks = config('custom.staff_auth_parks');
        $vpl_number = $staffOrder->vpl_number;
        $input = [
            'type'        => config('custom.staff_auth_type'),
            'share_count' => config('custom.staff_share_count'),
            'share'       => config('custom.staff_share_count') > 0 ? 1: 0,
            'mobile'      => $staffOrder->mobile,
            'validbtime'  => date('Y-m-d H:i:s', $staffOrder->valid_time_start),
            'validetime'  => date('Y-m-d H:i:s', $staffOrder->valid_time_end),
            'vpl_number'  => $staffOrder->vpl_number,

            'username'    => $staffOrder->staff_name,
            'email'       => '',
            'operator_id' => 0,
            'operator'    => '员工车接口',
            'priority'    => 2,
            'images'      => '',
        ];


        foreach ($parks as $park) {
            $data = $input;

            // 同一车场 车辆 一个时间段里只有一次
            $carAuths = CarAuth::where('park_code', $park)
                                ->select('id')
                                ->where('vpl_number', 'like', '%'.$vpl_number.'%')
                                ->where('validbtime', '<=', $data['validbtime'])
                                ->where('validetime', '>=', $data['validbtime'])
                                ->get();
            // $carAuths = $this->carAuthRepository->findWhere([
            //     'park_code' => $park,
            //     ['vpl_number', 'like', '%'.$vpl_number.'%' ],
            //     ['validbtime', '<=', $data['validbtime']],
            //     ['validetime', '>=', $data['validbtime']]
            // ])->all(["id"]);

            if(obj2arr($carAuths)){
                $this->log('已存在的此车辆授权时间段有重叠');
                continue;
            }

            $carAuths = CarAuth::where('park_code', $park)
                                ->select('id')
                                ->where('vpl_number', 'like', '%'.$vpl_number.'%')
                                ->where('validbtime', '<=', $data['validetime'])
                                ->where('validetime', '>=', $data['validetime'])
                                ->get();
            // $carAuths = $this->carAuthRepository->findWhere([
            //     'park_code' => $park,
            //     ['vpl_number', 'like', '%'.$vpl_number.'%' ],
            //     ['validbtime', '<=', $data['validetime']],
            //     ['validetime', '>=', $data['validetime']]
            // ])->all(["id"]);

            if(obj2arr($carAuths)){
                $this->log('已存在的此车辆授权时间段有重叠');
                continue;
            }

            $data['park_code'] = $park;
            $data['cardno']    = sprintf('%sNO%s', $staffOrder->order_no, $park);
            $data['serial_no'] = sprintf('%sSN%s', $staffOrder->order_no, $park);
            $data['option']    = 'add';

            // $carAuths =  $this->carAuthLogRepository->create($data);
            $carAuths =  CarAuthLog::create($data);

            $data['validbtime'] = strtotime($data['validbtime']);
            $data['validetime'] = strtotime($data['validetime']);

            if($carAuths) {
                $data['vpl_number'] = sprintf('[["%s",""]]', $vpl_number);

                // 查看返回状态
                $this->log('开始传递 CAR data');
                $this->log('参数数据:'.json_encode($data));
                $res = $this->sendAuthData($data);
                $this->log('返回参数：'.json_encode($res));
                if($res['code'] == 0) {
                    CarAuthLog::where('id', $carAuths->id)->update(['issued_status' => 1]);
                    // $this->carAuthLogRepository->update(['issued_status' => 1], $carAuths->id);
                } else {
                    CarAuthLog::where('id', $carAuths->id)->update(['issued_status' => 2]);
                    // $this->carAuthLogRepository->update(['issued_status' => 2], $carAuths->id);
                }
            }
        }
        $this->log('正在下发授权中......');
        return true;
    }


    // 下发授权
    public function issueAuthStaff($parks='', $vpl_number='', $mobile='', $name='')
    {

        $vpl_number = $vpl_number;
        $time_start = '2019-01-01 00:00:00';
        $time_end   = '2020-01-01 00:00:00';
        $input = [
            'type'        => config('custom.staff_auth_type'),
            'share_count' => config('custom.staff_share_count'),
            'share'       => config('custom.staff_share_count') > 0 ? 1: 0,
            'mobile'      => $mobile,
            'validbtime'  => $time_start,
            'validetime'  => $time_end,
            'vpl_number'  => $vpl_number,

            'username'    => $name,
            'email'       => '',
            'operator_id' => 0,
            'operator'    => '员工车接口',
            'priority'    => 2,
            'images'      => '',
        ];



        foreach ($parks as $park) {
            $data = $input;

            // 同一车场 车辆 一个时间段里只有一次
            $carAuths = CarAuth::where('park_code', $park)
                                ->select('id')
                                ->where('vpl_number', 'like', '%'.$vpl_number.'%')
                                ->where('validbtime', '<=', $data['validbtime'])
                                ->where('validetime', '>=', $data['validbtime'])
                                ->first();
            if($carAuths){
                CarAuth::where('id', $carAuths->id)->delete();
                echo "已存在的此车辆授权时间段有重叠\n";
            }

            $carAuths = CarAuth::where('park_code', $park)
                                ->select('id')
                                ->where('vpl_number', 'like', '%'.$vpl_number.'%')
                                ->where('validbtime', '<=', $data['validetime'])
                                ->where('validetime', '>=', $data['validetime'])
                                ->first();
            if($carAuths){
                CarAuth::where('id', $carAuths->id)->delete();
                echo "已存在的此车辆授权时间段有重叠\n";
            }

            // continue;

            $order_no = md5(uniqid(true) . rand(1000, 9999));

            $data['park_code'] = $park;
            $data['cardno']    = sprintf('%sNO%s', $order_no, $park);
            $data['serial_no'] = sprintf('%sSN%s', $order_no, $park);
            $data['option']    = 'add';

            // $carAuths =  $this->carAuthLogRepository->create($data);
            $carAuths =  CarAuthLog::create($data);

            $data['validbtime'] = strtotime($data['validbtime']);
            $data['validetime'] = strtotime($data['validetime']);

            if($carAuths) {
                $data['vpl_number'] = sprintf('[["%s",""]]', $vpl_number);

                // 查看返回状态
                $this->log('开始传递 CAR data');
                $this->log('参数数据:'.json_encode($data));
                $res = $this->sendAuthData($data);
                $this->log('返回参数：'.json_encode($res));
                if($res['code'] == 0) {
                    CarAuthLog::where('id', $carAuths->id)->update(['issued_status' => 1]);
                    // $this->carAuthLogRepository->update(['issued_status' => 1], $carAuths->id);
                } else {
                    CarAuthLog::where('id', $carAuths->id)->update(['issued_status' => 2]);
                    // $this->carAuthLogRepository->update(['issued_status' => 2], $carAuths->id);
                }
            }
        }

    }


    // 下发授权
    public function issueAuthFix($parks='', $vpl_number='', $mobile='', $name='', $type=8)
    {

        $time_start = '2019-01-01 00:00:00';
        $time_end   = '2020-01-01 00:00:00';
        $input = [
            'type'        => $type,
            'share_count' => config('custom.staff_share_count'),
            'share'       => config('custom.staff_share_count') > 0 ? 1: 0,
            'mobile'      => $mobile,
            'validbtime'  => $time_start,
            'validetime'  => $time_end,
            'vpl_number'  => $vpl_number,

            'username'    => $name,
            'email'       => '',
            'operator_id' => 0,
            'operator'    => '员工车接口',
            'priority'    => 2,
            'images'      => '',
        ];


        foreach ($parks as $park) {
            $data = $input;

            $order_no = md5(uniqid(true) . rand(1000, 9999));

            $data['park_code'] = $park;
            $data['cardno']    = sprintf('%sNO%s', $order_no, $park);
            $data['serial_no'] = sprintf('%sSN%s', $order_no, $park);
            $data['option']    = 'add';

            // delete auth
            // CarAuth::where("park_code", $data['park_code'])
            //             ->where("vpl_number", $vpl_number)
            //             ->delete();

            // continue;

            // $carAuths =  $this->carAuthLogRepository->create($data);
            $carAuths =  CarAuthLog::create($data);

            $data['validbtime'] = strtotime($data['validbtime']);
            $data['validetime'] = strtotime($data['validetime']);

            if($carAuths) {
                $data['vpl_number'] = sprintf('[["%s",""]]', $vpl_number);

                // 查看返回状态
                $this->log('开始传递 CAR data');
                $this->log('参数数据:'.json_encode($data));
                $res = $this->sendAuthData($data);
                $this->log('返回参数：'.json_encode($res));
                if($res['code'] == 0) {
                    CarAuthLog::where('id', $carAuths->id)->update(['issued_status' => 1]);
                    // $this->carAuthLogRepository->update(['issued_status' => 1], $carAuths->id);
                } else {
                    CarAuthLog::where('id', $carAuths->id)->update(['issued_status' => 2]);
                    // $this->carAuthLogRepository->update(['issued_status' => 2], $carAuths->id);
                }
            }

            // sleep(1);
        }

    }

    // 下发授权 失败的车
    public function issueAuthFaild()
    {
        // faild list
        $list = CarAuthLog::where('issued_status', 2)->get();
        $n = 0;
        foreach ($list as $item) {
            $data = [
                'type'        => $item->type,
                'share_count' => $item->share_count,
                'share'       => $item->share,
                'mobile'      => $item->mobile,
                'validbtime'  => $item->validbtime,
                'validetime'  => $item->validetime,
                'vpl_number'  => $item->vpl_number,
                'park_code'   => $item->park_code,

                'username'    => $item->username,
                'email'       => $item->email,
                'operator_id' => $item->operator_id,
                'operator'    => $item->operator,
                'priority'    => $item->priority,
                'images'      => $item->images,
            ];

            $data['cardno']    = sprintf('%sNO%s', $item->serial_no, $item->park_code);
            $data['serial_no'] = sprintf('%sSN%s', $item->serial_no, $item->park_code);
            $data['option']    = 'add';

            printf(
                "%04d - %s - %s - %s %s",
                ++$n,
                $data['park_code'],
                $data['vpl_number'],
                $data['username'],
                PHP_EOL
            );
            // continue;

            $carAuths =  CarAuthLog::create($data);

            $data['validbtime'] = strtotime($data['validbtime']);
            $data['validetime'] = strtotime($data['validetime']);

            if($carAuths) {
                $data['vpl_number'] = sprintf('[["%s",""]]', $data['vpl_number']);

                // 查看返回状态
                $this->log('开始传递 CAR data');
                $this->log('参数数据:'.json_encode($data));
                $res = $this->sendAuthData($data);
                $this->log('返回参数：'.json_encode($res));
                if($res['code'] == 0) {
                    CarAuthLog::where('id', $carAuths->id)->update(['issued_status' => 1]);
                    // $this->carAuthLogRepository->update(['issued_status' => 1], $carAuths->id);
                } else {
                    CarAuthLog::where('id', $carAuths->id)->update(['issued_status' => 2]);
                    // $this->carAuthLogRepository->update(['issued_status' => 2], $carAuths->id);
                }

                // delete faild
                CarAuthLog::where('id', $item->id)->delete();
            }

            sleep(1);
        }

    }

    // 下发授权 全通车
    public function issueAuthAll($vpl_number='', $mobile='', $name='')
    {
        // staff authed parks
        $parks = [
            // '7100000200',
            // '7100000285',
            // '7100000215',
            '7100000225',
            '7100000226',
            // '7100000183',
            // '7100000201',
            // '7100000228',
            // '7100000256',
            // '7100000252',
            // '7100000254',
            // '7100000259',
        ];
        $vpl_number = $vpl_number;
        $time_start = '2019-01-01 00:00:00';
        $time_end   = '2020-01-15 00:00:00';
        $input = [
            'type'        => 9,
            'share_count' => config('custom.staff_share_count'),
            'share'       => config('custom.staff_share_count') > 0 ? 1: 0,
            'mobile'      => $mobile,
            'validbtime'  => $time_start,
            'validetime'  => $time_end,
            'vpl_number'  => $vpl_number,

            'username'    => $name,
            'email'       => '',
            'operator_id' => 0,
            'operator'    => '员工车接口',
            'priority'    => 2,
            'images'      => '',
        ];


        foreach ($parks as $park) {
            $data = $input;


            // 同一车场 车辆 一个时间段里只有一次
            $carAuths = CarAuth::where('park_code', $park)
                                ->select('id')
                                ->where('vpl_number', 'like', '%'.$vpl_number.'%')
                                ->where('validbtime', '<=', $data['validbtime'])
                                ->where('validetime', '>=', $data['validbtime'])
                                ->first();
            if($carAuths){
                CarAuth::where('id', $carAuths->id)->delete();
                echo "已存在的此车辆授权时间段有重叠\n";
            }

            $carAuths = CarAuth::where('park_code', $park)
                                ->select('id')
                                ->where('vpl_number', 'like', '%'.$vpl_number.'%')
                                ->where('validbtime', '<=', $data['validetime'])
                                ->where('validetime', '>=', $data['validetime'])
                                ->first();
            if($carAuths){
                CarAuth::where('id', $carAuths->id)->delete();
                echo "已存在的此车辆授权时间段有重叠\n";
            }

            // continue;

            $order_no = md5(uniqid(true) . rand(1000, 9999));

            $data['park_code'] = $park;
            $data['cardno']    = sprintf('%sNO%s', $order_no, $park);
            $data['serial_no'] = sprintf('%sSN%s', $order_no, $park);
            $data['option']    = 'add';

            // $carAuths =  $this->carAuthLogRepository->create($data);
            $carAuths =  CarAuthLog::create($data);

            $data['validbtime'] = strtotime($data['validbtime']);
            $data['validetime'] = strtotime($data['validetime']);

            if($carAuths) {
                $data['vpl_number'] = sprintf('[["%s",""]]', $vpl_number);

                // 查看返回状态
                $this->log('开始传递 CAR data');
                $this->log('参数数据:'.json_encode($data));
                $res = $this->sendAuthData($data);
                $this->log('返回参数：'.json_encode($res));
                if($res['code'] == 0) {
                    CarAuthLog::where('id', $carAuths->id)->update(['issued_status' => 1]);
                    // $this->carAuthLogRepository->update(['issued_status' => 1], $carAuths->id);
                } else {
                    CarAuthLog::where('id', $carAuths->id)->update(['issued_status' => 2]);
                    // $this->carAuthLogRepository->update(['issued_status' => 2], $carAuths->id);
                }
            }
        }
        $this->log('正在下发授权中......');
        return true;
    }


    public function deleteByVpl($vpl = '')
    {
        if (empty($vpl)) {
            echo '车牌号不正确。';
            return false;
        }

        $carAuths = CarAuth::where('vpl_number', $vpl)->get();

        $this->log('CARAUTH_DELETE_VPL: '. $vpl);
        foreach ($carAuths as $carAuth) {
            $this->delete($carAuth);
        }

    }

    /**
     * Remove the specified CarAuth from storage.
     * DELETE /carAuths/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function delete($carAuth)
    {
        if (empty($carAuth)) {
            $this->log('CARAUTH_DELETE: 没有此授权');
            return false;
        }

        $this->log('CARAUTH_DELETE_SN: '. $carAuth->serial_no);

        $carAuth = obj2arr($carAuth);
        unset($carAuth['id']);
        $carAuth['option'] = 'delete';
        unset($carAuth['created_at']);
        unset($carAuth['updated_at']);
        unset($carAuth['organization']);
        unset($carAuth['organizations']);
        // $this->carAuthLogRepository->create($carAuth);
        CarAuthLog::create($carAuth);
        $data = [
            'serial_no' => $carAuth['serial_no'],
            'cardno'    => $carAuth['cardno'],
            'park_code' => $carAuth['park_code']
        ];
        $res = $this->deleteAuth($data);
        $this->log(json_encode($res));
        if($res['code'] == 0){
            $this->log('CARAUTH_DELETE: 正在删除授权中.....');
            return true;
        }

        $this->log('CARAUTH_DELETE: 授权删除失败');
        return false;
    }


    /**
     * 授权监控日志
     * @param $logdata
     */
    public function log($logdata){
        $log = new Logger('air_port');
        $log->pushHandler(new StreamHandler(storage_path('logs/car_auth-'.date("Y-m-d").'.log'),Logger::INFO) );
        $log->addInfo($logdata);
    }

}